﻿using BCZadmin.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BCZadmin.Helper;
using Newtonsoft.Json;
using System.Net;
using System.IO;

namespace BCZadmin
{
    public partial class ModelForm : Form
    {
        public DbModel type = null;
        public string control = "";
        public string Baseurl;
        private Main Father;
        private Dictionary<string, string> modelkey = new Dictionary<string, string>{
          {typeof(AdminInf).ToString(),"A_Id"},
          {typeof(PlanInf).ToString(),"P_Id"},
          {typeof(WordInf).ToString(),"W_Id"},
          {typeof(WordGroupInf).ToString(),"WG_Id"},
          {typeof(UserInf).ToString(),"U_Id"},
          {typeof(RemenberInf).ToString(),"U_Id"},
        };//类型对主键
        public ModelForm(string url, Main father)
        {
            InitializeComponent();
            Father = father;
            Baseurl = url;
        }
        public void ChangeSize(int x, int y)
        {
            this.Size = new Size(x, y);
        }
        public void Alert(object sender, EventArgs e)
        {
            if (Edit(false) == "true")
            {
                Father.AddLog("修改成功");
                Father.LoadPage("getall");
            }
            else
            {
                Father.AddLog("修改失败");
            }
        }
        public void Add(object sender, EventArgs e)
        {
            if (Edit(true) == "true")
            {
                Father.AddLog("添加成功");
                Father.LoadPage("getall");
            }
            else
            {
                Father.AddLog("添加失败");
            }
        }
        public void Query(object sender, EventArgs e)
        {
            var value = GetFileValue();
            if (value == null)
            {
                Father.LoadPage("getall");
                return;
            }
            var key = "";
            foreach (string file in value.Keys)
            {
                if (key == "")
                    key += file;
                else
                    key += "," + file;
            }
            value.Add("keys", key);
            Father.LoadPage("Query", value);
        }
        public void reset(object sender, EventArgs e)
        {
            foreach (Control c in this.Controls)
            {
                if (c.GetType().ToString() == "System.Windows.Forms.TextBox"
                    || c.GetType().ToString() == "System.Windows.Forms.RichTextBox")
                    c.Text = "";
            }
        }
        public string Edit(bool isadd)
        {
            //发送 一个 josn字符串
            var value = GetFileValue();
            foreach (System.Reflection.PropertyInfo inf in type.GetType().GetProperties())
            {
                if (!value.ContainsKey(inf.Name))
                    continue;
                if (value[inf.Name] == "" || value[inf.Name] == null)
                    continue;
                try
                {
                    var st = value[inf.Name].ToString();
                    inf.SetValue(type, st, null);
                }
                catch
                {
                    try
                    {
                        var it = Convert.ToInt32(value[inf.Name]);
                        inf.SetValue(type, it, null);
                    }
                    catch
                    {
                        var it = Convert.ToDateTime(value[inf.Name]);
                        inf.SetValue(type, it, null);
                    }
                }
            }
            Dictionary<string, string> httpinf = new Dictionary<string, string>();
            httpinf.Add("rd", JsonConvert.SerializeObject(type).Replace("\''", "\'"));
            return HttpHelper.GetResponseString(HttpHelper.CreatePostHttpResponse(Baseurl + "/" + control + "/" + (isadd ? "add" : "alert"), httpinf, 100, "", null));
        }
        private Dictionary<string, string> GetFileValue()
        {
            Dictionary<string, string> value = new Dictionary<string, string>();
            foreach (Control c in this.Controls)
            {
                if (c.GetType().ToString() == "System.Windows.Forms.TextBox"
                    || c.GetType().ToString() == "System.Windows.Forms.DateTimePicker" ||
                    c.GetType().ToString() == "System.Windows.Forms.RichTextBox")
                    if (c.Text != "")
                        value.Add(c.Name.Replace("Tb_", ""), c.Text);
                if (c.GetType().ToString() == "System.Windows.Forms.PictureBox")
                    value.Add(c.Name.Replace("Tb_", ""), ((PictureBox)c).Tag == null ? null : ((PictureBox)c).Tag.ToString());
                if (c.GetType().ToString() == "System.Windows.Forms.Button" && c.Tag as Dictionary<string, string> != null)
                    value.Add(c.Name.Replace("Tb_", ""), (((Button)c).Tag as Dictionary<string, string>)["server"]);
                if (c.GetType().ToString() == "System.Windows.Forms.Button" && c.Tag as Play != null)
                    value.Add(c.Name.Replace("Tb_", ""), ((c as Button).Tag as Play).interneturl);
            }
            if (value.Values.Count == 0)
                return null;
            return value;
        }
        public void Uppic(object sender, EventArgs e)
        {
            OpenFileDialog filedialog = new OpenFileDialog();
            filedialog.Filter = "图片(*.jpg,*.bmp)|*.jpg;*.bmp";//|所有文件(*.*)|*.*
            string localpath = "";
            if (filedialog.ShowDialog() != DialogResult.OK)
                return;
            var pb = sender as PictureBox;
            pb.Image = Image.FromFile(filedialog.FileName);
            localpath = filedialog.FileName;
            if (localpath != "")
            {
                var key = modelkey[type.GetType().ToString()];
                Control tb = this.Controls.Find("Tb_" + key, true)[0];
                var param = new Dictionary<string, string>();
                param.Add("key", (tb as TextBox).Text);//主键
                param.Add("typename", type.ToString().Replace("BCZadmin.Model.", ""));//表名
                param.Add("picfile", (sender as PictureBox).Name.Replace("Tb_", ""));//图片字段
                param.Add("type", "jpg");
                pb.Tag = PostFile(Baseurl + "/File/UpFile", param, localpath);

            }

        }
        private string PostFile(string Url, Dictionary<string, string> param, string localpath)
        {
            WebClient oWebClient = new WebClient();
            oWebClient.Credentials = CredentialCache.DefaultCredentials;
            oWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            foreach (string key in param.Keys)
                oWebClient.Headers.Add(key, param[key]);
            byte[] fileb = oWebClient.UploadFile(Url, "POST", localpath);
            var rt = System.Text.Encoding.Default.GetString(fileb);
            if (rt != "error")
            {
                Father.AddLog("上传文件成功");
            }
            Father.LoadPage("getall");
            return rt;
        }
        public void UpMp3(object sender, EventArgs e)
        {
            OpenFileDialog filedialog = new OpenFileDialog();
            filedialog.Filter = "音频(*.mp3)|*.mp3";//|所有文件(*.*)|*.*
            string localpath = "";
            if (filedialog.ShowDialog() != DialogResult.OK)
                return;
            var pb = (sender as Button).Tag as Button;
            localpath = filedialog.FileName;
            if (localpath != "")
            {
                var key = modelkey[type.GetType().ToString()];
                Control tb = this.Controls.Find("Tb_" + key, true)[0];
                var param = new Dictionary<string, string>();
                param.Add("key", (tb as TextBox).Text);//主键
                param.Add("typename", type.ToString().Replace("BCZadmin.Model.", ""));//表名
                param.Add("picfile", ((sender as Button).Tag as Button).Name.Replace("Tb_", ""));//文件字段  
                param.Add("type", "mp3");
                (pb.Tag as Dictionary<string, string>)["local"] = localpath;
                (pb.Tag as Dictionary<string, string>)["server"] = PostFile(Baseurl + "/File/UpFile", param, localpath);
            }
        }
        public void Button_PlayMusic(object sender, EventArgs e)
        {
            var bt = sender as Button;
            var mc = new Music((bt.Tag as Dictionary<string, string>)["local"]);
            if (mc == null)
                return;
            mc.PlayMusic();
        }
        public void ShowVideo(object sender, EventArgs e)
        {
            Play play = (sender as Button).Tag as Play;
            if (play.localurl == null || play == null)
            {
                (new Message("视屏还没有加载到本地请稍等....")).Show();
                return;
            }
            var local = play.localurl;
            var internte = play.interneturl;
            play.ShowDialog();
            (sender as Button).Tag = new Play() { localurl = local, interneturl = internte };//对象被销毁创建新的对象留下一次开启窗口
        }
        public void UpMp4(object sender, EventArgs e)
        {
            OpenFileDialog filedialog = new OpenFileDialog();
            filedialog.Filter = "视频(*.mp4)|*.mp4";//|所有文件(*.*)|*.*
            string localpath = "";
            if (filedialog.ShowDialog() != DialogResult.OK)
                return;
            var pb = (sender as Button).Tag as Button;
            localpath = filedialog.FileName;
            (((sender as Button).Tag as Button).Tag as Play).localurl = localpath;
            if (localpath != "")
            {
                var key = modelkey[type.GetType().ToString()];
                Control tb = this.Controls.Find("Tb_" + key, true)[0];
                var param = new Dictionary<string, string>();
                param.Add("key", (tb as TextBox).Text);//主键
                param.Add("typename", type.ToString().Replace("BCZadmin.Model.", ""));//表名
                param.Add("picfile", ((sender as Button).Tag as Button).Name.Replace("Tb_", ""));//文件字段  
                param.Add("type", "mp4");
                (((sender as Button).Tag as Button).Tag as Play).interneturl = PostFile(Baseurl + "/File/UpFile", param, localpath);
            }
        }
    }
}
